<?php

class User extends Base {
    CONST STATUS_ACTIVE = 1;
    CONST STATUS_BLOCKED = 0;

    protected function init() {
        parent::init();

        $this->attributes['id'] = 0;
        $this->attributes['username'] = '';
        $this->attributes['password'] = '';
        $this->attributes['email'] = '';
        $this->attributes['status'] = self::STATUS_BLOCKED;
        $this->attributes['salt'] = '';
    }

    /**
     * Load or new a user
     * @param mixed $id
     * @throws Exception
     */
    public function __construct($id = null) {
        $this->init();

        if (!empty($id)) {
            if ($id instanceof stdClass) { // is a DB row
                if (!$this->load($id->id)) {
                    throw new Exception("Fail to load id");
                }
            } else if (is_string($id)) { // if this is a username
                $id = get_user_by_username($id);
                foreach ($id->attributes as $key => $value) {
                    $this->attributes[$key] = $value;
                }
            } else if ($id instanceof User) { // is a User object? Use a copy constructor
                foreach ($id->attributes as $key => $value) {
                    $this->attributes[$key] = $value;
                }
            } else if (is_numeric($id)) { // id is an int
                if (!$this->load($id)) {
                    throw new Exception("Fail to load id");
                }
            } else { // other, exception
                throw new Exception("Invalid parameter exception: Unrecognised Value.");
            }
        }
    }

    /**
     * Load the user's attributes
     *
     * @param $id user id
     * @return bool
     */
    protected function load($id) {
        $row = get_user_object_as_row($id);

        $obj_array = (array) $row;
        foreach ($obj_array as $key => $value) {
            $this->attributes[$key] = $value;
        }

        return true;
    }

    /**
     * Save this user to the database
     * @return bool|int
     */
    public function save() {
        return create_user(
            $this->get('id'),
            $this->get('username'),
            $this->get('password'),
            $this->get('salt'),
            $this->get('email'),
            $this->get('status')
        );
    }

    /**
     * Delete this user
     * @return true|false
     */
    public function delete() {
        // TODO:
        return false;
    }

    /**
     * Check the user if active or blocked
     * @return true|false
     */
    public function  isActive() {
        return ((int) $this->get('status')) == self::STATUS_ACTIVE;
    }

}

/**
 * Returns the user specific details of a user by a row
 * @param int $id
 * @return object|false
 */
function get_user_object_as_row($id=0) {
    $id = (int) $id;
	if (!$id) return false;

    return get_data_row("SELECT * from users where id=$id");
}

/**
 * Get user by given id
 * @param $id
 * @return User
 */
function get_user_by_id($id) {
    $id = (int) $id;
    return new User($id);
}

/**
 * Get user by user name
 * @param string $username the user's username
 * @return User|false  Depending on success
 */
function get_user_by_username($username) {
    $username = mysql_real_escape_string(trim($username));

    // TODO: should check ACL
    $row = get_data_row("SELECT u.* from users u where u.username='$username'");
    if ($row) {
        // TODO: cache the user id
        return new User($row);
    }

    return false;
}

/**
 * Create or update the table for a given user
 *
 * @param $id
 * @param $username
 * @param $password
 * @param $salt
 * @param $email
 * @param $status
 */
function create_user($id, $username, $password, $salt, $email, $status) {
    global $CONFIG;

    $id = (int) $id;
    $username = mysql_real_escape_string($username);
    $password = mysql_real_escape_string($password);
    $salt = mysql_real_escape_string($salt);
    $email = mysql_real_escape_string($email);
    $status = (int) $status;

    $row = get_user_object_as_row($id);
    if ($row) {
        // TODO: Exists and you should update it
        return $id;
    } else {
        // TODO: Insert new user row

        return $id; // new user id
    }

    return false; // fail
}